package org.ianaz.chessfx;

import java.io.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.application.Application;
import javafx.event.EventHandler;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Menu;
import javafx.scene.control.MenuBar;
import javafx.scene.control.MenuItem;
import javafx.scene.control.SeparatorMenuItem;
import javafx.scene.effect.InnerShadow;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;
import org.ianaz.chessfx.logic.*;

/**
 *
 * @author Silvio Rainoldi
 */
public class ChessFX extends Application {

    public int cellSize = 80;
    public int iconsSize = 48;
    Scene scene;
    StackPane root;
    Game game;
    Rectangle[][] graphicalCells = new Rectangle[8][8];
    static boolean waitingMove = false;

    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage primaryStage) {
        Player p1 = new Human();
        p1.setColor(Color.WHITE);
        p1.setMultiplier(1);
        Player p2 = new Human();
        p2.setColor(Color.BLACK);
        p2.setMultiplier(-1);
        game = new Game(p1, p2);
        primaryStage.setTitle("ianaz Chess");
        primaryStage.setResizable(false);
        // Create root pane
        root = new StackPane();
        // New Scene
        scene = new Scene(root);
        // Adding menubar
        addMenuBar();
        // Adding board
        addBoard();
        // Set Scene to the stage
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    private void addMenuBar() {
        // Menu Bar
        MenuBar menuBar = new MenuBar();
        Menu menuFile = new Menu("File");

        Menu menuHelp = new Menu("Help");

        // New game
        MenuItem newGameItem = new MenuItem("New Game");
        newGameItem.setDisable(true);
        menuFile.getItems().add(newGameItem);

        // Save item
        MenuItem saveItem = new MenuItem("Save");
        saveItem.setDisable(true);
        menuFile.getItems().add(saveItem);

        // Separator
        menuFile.getItems().add(new SeparatorMenuItem());

        // Exit item
        MenuItem exitItem = new MenuItem("Exit");
        menuFile.getItems().add(exitItem);

        menuBar.getMenus().add(menuFile);
        menuBar.getMenus().add(menuHelp);
        menuBar.setLayoutY(0);
        // Adding menu bar to the stage
        root.getChildren().add(menuBar);
    }

    private void addBoard() {
        // Board
        final Group board = new Group(new Rectangle(cellSize * 8, cellSize * 8));
        InputStream is = null;
        File f = null;

        // Cells
        for (int i = 0; i < game.getCells().length; i++) {
            for (int l = 0; l < game.getCells()[i].length; l++) {

                final Cell c = game.getCells()[l][i];
                final Rectangle cellR = new Rectangle(cellSize, cellSize, c.getColor());
                graphicalCells[l][i] = cellR;
                final Group cellGroup = new Group(cellR);
                

                cellGroup.setOnMouseEntered(new EventHandler<MouseEvent>() {

                    @Override
                    public void handle(MouseEvent arg0) {
                        InnerShadow is = new InnerShadow();
                        is.setOffsetX(1.0f);
                        is.setOffsetY(1.0f);
                        is.setColor(Color.ROYALBLUE);
                        cellR.setEffect(is);
                    }
                });
                cellGroup.setOnMouseExited(new EventHandler<MouseEvent>() {

                    @Override
                    public void handle(MouseEvent arg0) {
                        cellR.setEffect(null);
                    }
                });

                cellR.setX(l * cellSize);
                cellR.setY(i * cellSize);
                if (c.getFigure() != null) {
                    try {
                        f = new File("figures/" + c.getFigure().getPlayer().getColorString() + "_" + c.getFigure().getClass().getSimpleName() + ".png");
                        System.out.println(f.getAbsolutePath());

                        is = new BufferedInputStream(new FileInputStream(f));
                        Image img = new Image(is);
                        ImageView imgv = new ImageView(img);

                        imgv.setX(l * cellSize + ((cellSize - iconsSize) / 2));
                        imgv.setY(i * cellSize + ((cellSize - iconsSize) / 2));


                        cellGroup.setOnMouseClicked(new EventHandler<MouseEvent>() {


                            @Override
                            public void handle(MouseEvent arg0) {
                                System.out.println(String.valueOf(waitingMove));
                                if (waitingMove == true) {
                                    cellGroup.getChildren().add(graphicalCells[5][4]);
                                } else {
                                    clearCellsColor();
                                    boolean[][] possibleMoves = c.getFigure().getPossibleMoves();
                                    cellR.setFill(Color.CADETBLUE);
                                    for (int i = 0; i < possibleMoves.length; i++) {
                                        for (int l = 0; l < possibleMoves[i].length; l++) {
                                            if (possibleMoves[i][l] == true) {
                                                // There is at least one possible move, then set waitingMove on true
                                                waitingMove = true;
                                                // Change the color of the possible cells
                                                graphicalCells[i][l].setFill(Color.CADETBLUE);
                                            }
                                        }
                                    }
                                }

                            }
                        });


                        cellGroup.getChildren().add(imgv);
                    } catch (FileNotFoundException ex) {
                        Logger.getLogger(ChessFX.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
                board.getChildren().add(cellGroup);

            }
        }

        root.getChildren().add(board);
    }

    private void clearCellsColor() {
        for (int i = 0; i < graphicalCells.length; i++) {
            for (int l = 0; l < graphicalCells[i].length; l++) {
                graphicalCells[i][l].setFill(game.getCells()[i][l].getColor());
            }
        }
    }
}
